﻿/*
(c) 2010 - Open Source Business Foundation e. V. (www.osbf.de)
This software is provided under Microsoft Reciprocal License (Ms-RL)
(http://www.microsoft.com/opensource/licenses.mspx#Ms-RL)
All other rights reserved
*/


using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Web.UI.WebControls;
using MicroFormatProcessing;


namespace MicroFormatWebRole {
    public partial class Edit : System.Web.UI.Page {

        protected const string value_control = "tbValue";
        protected const string property_control = "lblProperty";

        private Session MySession;
        private string MyUser;
        private string MyTag;
        private string MyRowKey;
        private bool EditEnabled;
        private bool isNewMicroformat;
        private MicroFormat selectedMicroFormat = null;

        protected void Page_Load(object sender, EventArgs e) {
            this.MyTag = Request["tag"];
            this.MyUser = Request["user"];
            this.MyRowKey = Request["edit"];

            isNewMicroformat = "".Equals(MyRowKey);
            string sessionId = Request["sessionId"];
            if (sessionId == null) {
                sessionId = (Request.Cookies["session"] != null) ? Request.Cookies["session"]["id"] : null;
            }
            if (sessionId != null) {
                this.MySession = UserUtil.GetSesssion(sessionId);
            }
            if ((this.MyUser == null) && (this.MySession != null)) {
                this.MyUser = this.MySession.UserId;
            }

            this.EditEnabled = ((this.MySession != null) && (this.MySession.UserId.Equals(this.MyUser)));
            if (this.EditEnabled) {
                HeaderSectionLeft2.Visible = true;
                LoginLabel.Text = String.Format("Logged in as {0}", this.MyUser);
            } else {
                HeaderSectionLeft2.Visible = false;
            }
            if (!IsPostBack) {
                UpdateMfPropertyFromMfDefinition();
            } else {
                if (!isNewMicroformat)
                    GetMicroformat();
            }
        }

        protected void RemoveTags(TagRepository tagRepository) {
            foreach (string tagName in selectedMicroFormat.GetTagArray()) {
                IList<Tag> tags = tagRepository.FindByUserIdAndTagName(MyUser, tagName);
                foreach (Tag tag in tags) {
                    tag.RemoveReference(selectedMicroFormat.RowKey);
                    if (tag.GetReferenceCount() == 0) {
                        tagRepository.Delete(tag, false);
                    } else {
                        tagRepository.Update(tag, false);
                    }
                }
            }
            IList<Tag> tagsUntagged = tagRepository.FindByUserIdAndTagName(MyUser, Constants.UNTAGGED);
            foreach (Tag tag in tagsUntagged) {
                tag.RemoveReference(selectedMicroFormat.RowKey);
                tagRepository.Update(tag, false);
            }
            selectedMicroFormat.ClearTags();
        }

        protected void AddProperties() {
            selectedMicroFormat.ClearPoperties();
            foreach (GridViewRow row in MfPropertyGridView.Rows) {
                TextBox tbValue = row.FindControl(value_control) as TextBox;
                if (tbValue.Text != "") {
                    selectedMicroFormat.SetProperty(row.Cells[0].Text, tbValue.Text);
                }
            }
        }

        protected void AddTags(TagRepository tagRepository) {
            string fixTags = lbFixedLabel.Text;
            if (fixTags.Length > 0) {
                foreach (string tag in fixTags.Split(',')) {
                    selectedMicroFormat.AddTag(tag.Trim());
                }
            }
            string tagsString = tbTagged.Text;
            if (tagsString.Length > 0) {
                foreach (string tagString in tagsString.Split(',')) {
                    selectedMicroFormat.AddTag(tagString.Trim());
                    IList<Tag> tags = tagRepository.FindByUserIdAndTagName(MyUser, tagString.Trim());
                    if (tags.Count > 0) {
                        foreach (Tag tag in tags) {
                            tag.AddReference(selectedMicroFormat.RowKey);
                            tagRepository.Update(tag, false);
                        }
                    } else {
                        Tag tag = new Tag(MyUser, tagString.Trim());
                        tag.AddReference(selectedMicroFormat.RowKey);
                        tagRepository.Add(tag);
                    }
                }
            } else {
                selectedMicroFormat.AddTag(Constants.UNTAGGED);
                IList<Tag> tags = tagRepository.FindByUserIdAndTagName(MyUser, Constants.UNTAGGED);
                foreach (Tag tag in tags) {
                    tag.AddReference(selectedMicroFormat.RowKey);
                    tagRepository.Update(tag, false);
                }
            }
        }

        protected bool checkInput() {
            bool result = true;
            if (selectedMicroFormat.GetProperty(Constants.attribute_fn) == "") {
                StringBuilder name = new StringBuilder();
                foreach (string property in Constants.vCardsAttibutesName) {
                    if (selectedMicroFormat.GetProperty(property) != "") {
                        name.Append(selectedMicroFormat.GetProperty(property)).Append(" ");
                    }
                }
                selectedMicroFormat.SetProperty(Constants.attribute_fn, name.ToString().Trim());
                result = selectedMicroFormat.GetProperty(Constants.attribute_fn) != ""; 
             } 
            return result;
        }

        protected void OnSaveButtonClick(object sender, EventArgs e) {

            TagRepository tagRepository = new TagRepository();
            MicroFormatRepository mfRepository = new MicroFormatRepository();
            if (isNewMicroformat) {
                selectedMicroFormat = new MicroFormat();
                selectedMicroFormat.SetUserId(MyUser);
                selectedMicroFormat.FoundOnDate = DateTime.Now;
                selectedMicroFormat.Type = Constants.hCard;
            } 
            AddProperties();
            if (checkInput()) {
                selectedMicroFormat.Name = selectedMicroFormat.GetProperty("fn");
                if (isNewMicroformat) {
                    mfRepository.Add(selectedMicroFormat);
                } else {
                    RemoveTags(tagRepository);
                }
                AddTags(tagRepository);
                mfRepository.Update(selectedMicroFormat, !isNewMicroformat);
                back();
            } else {
                Response.Write("<script type='text/javascript'>alert('Please enter a name');</script>");
            }
        }

        protected void back() {
            StringBuilder url = new StringBuilder();
            url.Append("Browse.aspx?user=").Append(MyUser).Append("&tag=").Append(MyTag);
            Response.Redirect(url.ToString());
        }

        protected void OnCancelButtonClick(object sender, EventArgs e) {
            back();
        }

        protected void MfPropertyGridView_RowDataBound(object sender, GridViewRowEventArgs e) {
            e.Row.Cells[0].Visible = false;
            e.Row.Cells[1].Visible = false;
            if (e.Row.RowType == DataControlRowType.DataRow) {
                Label lblProperty = e.Row.FindControl(property_control) as Label;
                TextBox tbValue = e.Row.FindControl(value_control) as TextBox;
                lblProperty.Text = e.Row.Cells[0].Text;
                if (e.Row.Cells[1].Text != "" && e.Row.Cells[1].Text != "&nbsp;") {
                    tbValue.Text = e.Row.Cells[1].Text;
                }
            }
        }

        private void GetMicroformat() {
            string mfId = MyRowKey;
            if (mfId != null) {
                MicroFormatRepository mfRepository = new MicroFormatRepository();
                foreach (MicroFormat microFormat in mfRepository.FindByUserIdAndMfId(this.MyUser, mfId)) {
                    selectedMicroFormat = microFormat;
                }
            }
        }


        private void UpdateMfPropertyFromMfDefinition() {
            GetMicroformat();
            if (selectedMicroFormat != null) {
                selectedMicroFormat.DeSerializeAttributes();
                ContentSection.Visible = true;
                ContentTitle.Text = String.Format("{0} [{1}] Detail", selectedMicroFormat.Name, selectedMicroFormat.Type);
                ContentDate.Text = selectedMicroFormat.FoundOnDate.ToString("yyyy'-'MM'-'dd HH':'mm':'ss");
                ContentUrl.Text = selectedMicroFormat.FoundOnUrl;
                ContentUrl.NavigateUrl = selectedMicroFormat.FoundOnUrl;
                StringBuilder sbTag = new StringBuilder();
                StringBuilder sbFixed = new StringBuilder();
                foreach (string tag in selectedMicroFormat.GetTagArray()) {
                    if (Constants.ME.Equals(tag) || Constants.FRIENDS.Equals(tag)) {
                        if (sbFixed.Length > 0) {
                            sbFixed.Append(", ");
                        }
                        sbFixed.Append(tag);
                    } else if (!Constants.UNTAGGED.Equals(tag)) {
                        if (sbTag.Length > 0) {
                            sbTag.Append(", ");
                        }
                        sbTag.Append(tag);
                    }
                }
                tbTagged.Text = sbTag.ToString();
                lbFixedLabel.Text = sbFixed.ToString();
            } else {
                ContentSection.Visible = true;
                ContentTitle.Text = String.Format("{0} [{1}] Detail", "", Constants.hCard);
                ContentDate.Text = DateTime.Now.ToString("yyyy'-'MM'-'dd HH':'mm':'ss");
                ContentUrl.Text = "";
                ContentUrl.NavigateUrl = "";

                tbTagged.Text = MyTag;
                lbFixedLabel.Text = "";
            }

            MfPropertyGridView.DataSource = CreateMfPropertyGridDataSource(selectedMicroFormat);
            MfPropertyGridView.DataBind();
        }

        private DataView CreateMfPropertyGridDataSource(MicroFormat microFormat) {
            DataTable dt = new DataTable();
            dt.Columns.Add(new DataColumn("Property", typeof(String)));
            dt.Columns.Add(new DataColumn("Value", typeof(String)));
            string[] propertyNames = Constants.vCardAttribute.Keys.ToArray<string>();
            foreach (string propertyName in propertyNames) {
                DataRow dr = dt.NewRow();
                dr[0] = propertyName;
                if (isNewMicroformat)
                   dr[1] = "";
                else
                   dr[1] = microFormat.GetProperty(propertyName);
                dt.Rows.Add(dr);
            }
            return new DataView(dt);
        }

    }

  
}